package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private OrganAddressDao organAddressDao;



    //体检预约
    public Result order(Map map) throws Exception {

        //1.检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.检查预约日期是否预约已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number) {
            //预约已满，不能预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //检查当前用户是否为会员，根据手机号判断
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);

        //3.防止重复预约
        if (member != null) {
            Integer memberId = member.getId();
            int setmealId = Integer.parseInt((String) map.get("setmealId"));
            Order order = new Order(memberId, date, null, null, setmealId);
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                //已经完成了预约，不能重复预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }
        //可以预约，设置预约人数加一
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        // 4.检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        if (member == null) {
            //当前用户不是会员，需要添加到会员表
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //5.保存预约信息到预约表
        Order order = new Order(member.getId(), date, (String) map.get("orderType"), Order.ORDERSTATUS_NO,
                Integer.parseInt((String) map.get("setmealId")));
        String address = (String) map.get("address");
        OrganAddress organAddress = organAddressDao.selectByAddress(address);
        order.setOrganId(organAddress.getId());
        orderDao.add(order);
        
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());

    }

    //根据id查询预约信息，包括体检人信息、套餐信息，机构地址
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        if (map != null) {
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));

            //根据机构id查询地址
            Integer organId = (Integer) map.get("organId");
            OrganAddress organ = organAddressDao.findById(organId);
            map.put("address",organ.getAddress());
        }
        return map;
    }



    @Override
    public List<Integer> findOrderCountByDate(List<String> days) {
        List<Integer> list = new ArrayList<>();
        for(String day : days){
            Integer count = orderDao.findOrderCountByDate(day);
            list.add(count);
        }
        return list;
    }

    @Override
    public List<Integer> findVisitsCountByDate(List<String> days) {
        List<Integer> list = new ArrayList<>();
        for(String day : days){
            Integer count = orderDao.findVisitsCountByDate(day);
            list.add(count);
        }
        return list;
    }

    //根据日期范围，预约类型、状态、以及会员名称和电话号码分页查询订单信息
    @Override
    public PageResult findOrderInfosByConditions(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        String orderStatus = queryPageBean.getOrderStatus();
        String orderType = queryPageBean.getOrderType();
        String[] queryTime = queryPageBean.getQueryTime();
        String startDate = null;
        String endDate = null;
        //截取日期字符串
        if (queryTime != null && queryTime.length > 0) {
            startDate = parseDateZone(queryTime[0]);
            endDate = parseDateZone(queryTime[1]);
        }
        Map<String, String> map = new HashMap<>();
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("queryString", queryString);
        map.put("orderStatus", orderStatus);
        map.put("orderType", orderType);
        PageHelper.startPage(currentPage, pageSize);
        Page<Map<String, Object>> page = orderDao.findOrderInfosByConditions(map);
        //处理日期格式
        if (page != null) {
            for (Map<String, Object> resultMap : page) {
                Date orderDate = (Date) resultMap.get("orderDate");
                String Date = null;
                try {
                    Date = DateUtils.parseDate2String(orderDate);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                resultMap.put("orderDate", Date);
            }
        }
        return new PageResult(page.getTotal(), page.getResult());
    }



    //电话预约
    @Override
    public Result orderByCall(Map map, String[] setmealIds) throws Exception {

        //查询所选日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        String date = parseDateZone(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(date));
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //查询预约所选日期是否已约满
        int reservations = orderSetting.getReservations();
        int number = orderSetting.getNumber();
        if (reservations >= number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //查询该用户是否为会员，如果不是，注册该会员的信息
        String phoneNum = (String) map.get("phoneNum");
        Member member = memberDao.findByTelephone(phoneNum);
        if (member == null) {
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(phoneNum);
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        int oc = 0;//已经预约的套餐数量
        Integer memberId = member.getId();
        String message = "重复的预约：";
        //添加没有重复的预约
        for (int i = 0; i < setmealIds.length; i++) {
            int setmealId = Integer.parseInt(setmealIds[i]);
            Order order = new Order(memberId, DateUtils.parseString2Date(date), null, null, setmealId);
            List<Order> orders = orderDao.findByCondition(order);
            if (orders == null || orders.size() <= 0) {
                //根据机构电话查询机构信息
                String organPhoneNum = (String) map.get("organPhoneNum");
                OrganAddress organAddress = organAddressDao.findOrganByPhone(organPhoneNum);
                if(organAddress==null){
                    return new Result(false,"无效的机构电话");
                }
                order.setSetmealId(setmealId);
                order.setMemberId(memberId);
                order.setOrderType("电话预约");
                order.setOrderStatus("未到诊");
                order.setOrderDate(DateUtils.parseString2Date(date));
                order.setOrganId(organAddress.getId());
                orderDao.add(order);
                orderSetting.setReservations(reservations + 1);
                orderSettingDao.editReservationsByOrderDate(orderSetting);
            } else {
                Setmeal setmeal = setmealDao.findById(setmealId);
                String name = setmeal.getName();
                message = message + name + ".  ";
                oc += 1;
            }
        }
        if (oc > 0) {
            return new Result(false, message);
        }

        return new Result(true, MessageConstant.ORDER_SUCCESS);
    }

    //转换日期格式
    public String parseDateZone(String orderDate){
        orderDate = orderDate.replace("Z", " UTC");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        String result = null;
        try {
            date = format.parse(orderDate);
            result = defaultFormat.format(date);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    //更新预约订单
    @Override
    public Result update(Map<String, Object> map, int id) throws Exception {

        String memberName = (String) map.get("member");
        String orderStatus = (String) map.get("orderStatus");

        //1.检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        if (orderDate.length()>10) {
             orderDate = parseDateZone(orderDate);
        }
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.检查预约日期是否预约已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number) {
            //预约已满，不能预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        Member member = new Member();
        member.setName(memberName);
        memberDao.edit(member);
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("id", id);
        orderMap.put("orderDate", orderDate);
        orderMap.put("orderStatus", orderStatus);
        orderDao.update(orderMap);
        orderSetting.setReservations(reservations + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }

    //删除预约
    @Override
    public void delete(int id) {
        orderDao.delete(id);
    }

    //按钮改变预约状态
    @Override
    public void changeOrderStatus(Map<String, Object> map) {
        System.out.println(map);
        orderDao.update(map);
    }
}
